package com.xncoding.trans.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class CacheCleanupService {

    @Autowired
    RedisCacheManager cacheManager;

    /**
     * 删除缓存中所有以指定前缀开头的项（针对ConcurrentMapCacheManager）
     * 注意：这个方法假设你正在使用ConcurrentMapCacheManager，并且不推荐在生产环境中直接使用。
     *
     * @param cacheName 缓存的名称
     * @param prefix    要删除的前缀（不包括我们添加到键中的'-prefix'）
     */
    public void evictCacheByPrefix(String cacheName, String prefix) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null && cache instanceof org.springframework.cache.concurrent.ConcurrentMapCache) {
            org.springframework.cache.concurrent.ConcurrentMapCache concurrentMapCache = (org.springframework.cache.concurrent.ConcurrentMapCache) cache;
            ConcurrentHashMap<?, ?> map = (ConcurrentHashMap<?, ?>) concurrentMapCache.getNativeCache();

            // 遍历并删除匹配前缀的键
            Iterator<?> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                String keyStr = key.toString();
                if (keyStr.startsWith(prefix + "-prefix")) { // 注意这里添加了'-prefix'
                    iterator.remove();
                }
            }
        }
    }
}
